package com.zrl.project.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrl.project.common.ErrorCode;
import com.zrl.project.common.UserHolder;
import com.zrl.project.constant.RedisConstants;
import com.zrl.project.exception.BusinessException;
import com.zrl.project.mapper.UserMapper;
import com.zrl.project.model.VO.userVO.ModifyUserPasswordVO;
import com.zrl.project.model.entity.User;
import com.zrl.project.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.zrl.project.constant.UserConstant.PREFIX;
import static com.zrl.project.constant.UserConstant.USER_LOGIN_STATE;


/**
 * 用户服务实现类
 *
 * @author zrl
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {


    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        //非空
        if (StringUtils.isAnyBlank(userAccount,userPassword,checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //账户长度不小于四位
        if (userAccount.length() < 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户长度过短");
        }
        //账户密码不小于8位
        if (userPassword.length() < 8 || checkPassword.length() < 8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码长度过短");
        }
        //密码与校验密码相同
        if (!userPassword.equals(checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"两次密码不相同");
        }
        //账号不能重复
        User userAccount1 = query().eq("userAccount", userAccount).one();
        if (userAccount1 != null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户已存在");
        }

        //账户不能包含特殊字符

        String validPattern = "[`~!@#$%^&()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户包含特殊字符");
        }


        //加密并保存到数据库
        String encryptPassword = DigestUtils.md5DigestAsHex((PREFIX + userPassword).getBytes());
        User user = new User();
        user.setUserPassword(encryptPassword);
        user.setUserAccount(userAccount);
        user.setUserName("User_" + System.currentTimeMillis());

        boolean save = save(user);
        if (!save){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"注册失败");
        }

        return user.getId();
    }

    @Override
    public String userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //非空
        if (StringUtils.isAnyBlank(userAccount,userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR_IS_NULL);
        }
        //账户密码不小于四位
        if (userAccount.length() < 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR_User);
        }
        //账户密码不小于8位
        if (userPassword.length() < 8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR_User);
        }

        //加密
        String encryptPassword = DigestUtils.md5DigestAsHex((PREFIX + userPassword).getBytes());

        //账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户包含特殊字符");
        }

        //查询用户是否存在
        User user = query().eq("userAccount", userAccount)
                .eq("userPassword",encryptPassword)
                .one();

        //用户不存在
        if (user == null){
            log.info("user login failed ,userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户或密码错误");
        }

        //用户不存在
        if (user.getUserStatus() == 1){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号被封禁");
        }

        //用户脱敏
        user.setUserPassword("*");

        //7.保存用户信息到Redis中
        //7.1随机生成token,作为登录令牌
        String token = UUID.randomUUID().toString();
        //7.2将User对象转为Hash存储
        setRedisUser(token, user);
        //8返回token
        return token;
    }

    /**
     * 用户脱敏
     * @param originalUser 用户
     * @return
     */
    @Override
    public User getSafetyUser(User originalUser) {
        if(originalUser == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户不存在");
        }
        User safetyUser = new User();
        safetyUser.setId(originalUser.getId());
        safetyUser.setUserName(originalUser.getUserName());
        safetyUser.setUserAccount(originalUser.getUserAccount());
        safetyUser.setUserAvatar(originalUser.getUserAvatar());
        safetyUser.setGender(originalUser.getGender());
        safetyUser.setRole(originalUser.getRole());
        safetyUser.setPhone(originalUser.getPhone());
        safetyUser.setEmail(originalUser.getEmail());
        safetyUser.setUserStatus(originalUser.getUserStatus());
        safetyUser.setCreateTime(originalUser.getCreateTime());
        safetyUser.setSign(originalUser.getSign());
        return safetyUser;
    }

    @Override
    public int userLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }

    @Override
    public Long addUser(User user) {
        String userAccount = user.getUserAccount();
        String userPassword = user.getUserPassword();
        //非空
        if (StringUtils.isAnyBlank(userAccount,userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号或密码为空");
        }
        //账户长度不小于四位
        if (userAccount.length() < 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户长度过短");
        }
        //账户密码不小于8位
        if (userPassword.length() < 8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码长度过短");
        }
        //账号不能重复
        User userAccount1 = query().eq("userAccount", userAccount).one();
        if (userAccount1 != null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户已存在");
        }

        //账户不能包含特殊字符

        String validPattern = "[`~!@#$%^&()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户包含特殊字符");
        }


        //加密并保存到数据库
        String encryptPassword = DigestUtils.md5DigestAsHex((PREFIX + userPassword).getBytes());
        user.setUserPassword(encryptPassword);

        boolean save = save(user);
        if (!save){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"注册失败");
        }

        return user.getId();
    }

    @Override
    public List<User> searchUsers(String userName, String userAccount, Integer gender, Integer role, Integer userStatus) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(userName)){
            queryWrapper.like("userName",userName);
        }
        if (StringUtils.isNotBlank(userAccount)){
            queryWrapper.like("userAccount",userAccount);
        }
        if (role != null){
            queryWrapper.like("role",role);
        }
        if (userStatus!= null){
            queryWrapper.like("userStatus",userStatus);
        }
        if (gender != null){
            queryWrapper.like("gender",gender);
        }

        List<User> userList = list(queryWrapper);

        if (userList==null || userList.isEmpty()){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"无相关用户");
        }

        List<User> result = userList.stream().map(user -> {
            user.setUserPassword(null);
            return getSafetyUser(user);
        }).collect(Collectors.toList());
        return result;
    }

    @Override
    public boolean updateUserById(User newUser,HttpServletRequest request) {
        String token = request.getHeader("authorization");
        //获取用户id
        Long userId = newUser.getId();
        User user = getById(userId);
        //设置密码
        newUser.setUserPassword(user.getUserPassword());
        newUser.setIsDelete(user.getIsDelete());
        boolean b = updateById(newUser);
        if (!b){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"修改失败");
        }
        User result = getById(userId);
        if (newUser.getId()==UserHolder.getUser().getId()){
            setRedisUser(token,result);
        }
        return true;
    }

    private void setRedisUser(String token, User user) {
        Map<String, Object> userMap = BeanUtil.beanToMap(user,
                new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true).
                        setFieldValueEditor((fileName, fileVal) -> fileVal.toString())
        );
        //存储
        String tokenKey = RedisConstants.LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
        //设置token有效期
        stringRedisTemplate.expire(tokenKey, RedisConstants.LOGIN_USER_TTL, TimeUnit.SECONDS);
    }

    @Override
    public boolean modifyUserPassword(ModifyUserPasswordVO user) {
        if (user == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请输入旧密码或新密码");
        }

        //根据id获取当前用户信息，判断旧密码是否相同
        Long userId = user.getId();
        //当前用户信息
        User oldUser = getById(userId);
        //数据库中该用户的密码
        String oldUserPassword = oldUser.getUserPassword();

        //用户输入的旧密码,加密后比较
        String Password = user.getUserPassword();


        String userPassword = DigestUtils.md5DigestAsHex((PREFIX + Password).getBytes());

        if (!oldUserPassword.equals(userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"输入的旧密码错误");
        }

        //获取新密码
        String newUserPassword = user.getNewPassword();

        //账户密码不小于8位
        if (newUserPassword.length() < 8 || user.getCheckPassword().length() < 8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码长度过短");
        }

        //判断两次输入的密码是否相同
        if (!newUserPassword.equals(user.getCheckPassword())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"两次输入的新密码不同");
        }

        if (userPassword.equals(newUserPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"新密码与旧密码相同");
        }


        //加密并保存到数据库
        String encryptPassword = DigestUtils.md5DigestAsHex((PREFIX + newUserPassword).getBytes());
        oldUser.setUserPassword(encryptPassword);

        return updateById(oldUser);

    }

    @Override
    public Boolean ModifyConcernUser(Long userId) {
        Long currentUserId = UserHolder.getUser().getId();

        String fansKey = RedisConstants.FANS + userId;
        String followsKey = RedisConstants.FOLLOWS + currentUserId;

        if (followedUser(userId)){
            stringRedisTemplate.opsForSet().remove(fansKey,currentUserId.toString());
            stringRedisTemplate.opsForSet().remove(followsKey,userId.toString());
            return false;
        }else{
            stringRedisTemplate.opsForSet().add(fansKey,currentUserId.toString());
            stringRedisTemplate.opsForSet().add(followsKey,userId.toString());
            return true;
        }
    }

    @Override
    public Boolean concernUser(Long userId) {
        Long currentUserId = UserHolder.getUser().getId();

        String fansKey = RedisConstants.FANS + userId;
        String followsKey = RedisConstants.FOLLOWS + currentUserId;

        stringRedisTemplate.opsForSet().add(fansKey,currentUserId.toString());
        stringRedisTemplate.opsForSet().add(followsKey,userId.toString());
        return true;

    }
    @Override
    public Boolean noConcernUser(Long userId) {
        Long currentUserId = UserHolder.getUser().getId();

        String fansKey = RedisConstants.FANS + userId;
        String followsKey = RedisConstants.FOLLOWS + currentUserId;

        stringRedisTemplate.opsForSet().remove(fansKey,currentUserId.toString());
        stringRedisTemplate.opsForSet().remove(followsKey,userId.toString());
        return true;
    }

    @Override
    public Boolean followedUser(Long userId) {
        Long currentUserId = UserHolder.getUser().getId();
        String fansKey = RedisConstants.FANS + userId;
        String followsKey = RedisConstants.FOLLOWS + currentUserId;

        Set<String> fans = stringRedisTemplate.opsForSet().members(fansKey);
        if (fans== null || fans.isEmpty()){
            return false;
        }
        Set<String> follows = stringRedisTemplate.opsForSet().members(followsKey);
        if (follows== null || follows.isEmpty()){
            return false;
        }
        return Boolean.TRUE.equals(fans.contains(currentUserId.toString()))
                &&
                Boolean.TRUE.equals(follows.contains(userId.toString()));
    }

    @Override
    public List<User> getMyFans() {
        Long id = UserHolder.getUser().getId();
        String myFans = RedisConstants.FANS + id;
        Set<String> fans = stringRedisTemplate.opsForSet().members(myFans);
        if (fans == null || fans.isEmpty()){
            return Collections.emptyList();
        }
        List<Long> userIds = fans.stream().map(Long::valueOf).collect(Collectors.toList());
        return listByIds(userIds);
    }

    @Override
    public List<User> getMyFollows() {
        Long id = UserHolder.getUser().getId();
        String Follows = RedisConstants.FOLLOWS + id;
        Set<String> follows = stringRedisTemplate.opsForSet().members(Follows);
        if (follows == null || follows.isEmpty()){
            return Collections.emptyList();
        }
        List<Long> userIds = follows.stream().map(Long::valueOf).collect(Collectors.toList());
        return listByIds(userIds);
    }

    @Override
    public Boolean removeFan(Long userId) {

        Long currentUserId = UserHolder.getUser().getId();
        String fansKey = RedisConstants.FANS + currentUserId;
        String followsKey = RedisConstants.FOLLOWS + userId;

        Set<String> fans = stringRedisTemplate.opsForSet().members(fansKey);
        if (fans== null || fans.isEmpty()){
            return false;
        }
        Set<String> follows = stringRedisTemplate.opsForSet().members(followsKey);
        if (follows== null || follows.isEmpty()){
            return false;
        }
        boolean flag = Boolean.TRUE.equals(fans.contains(userId.toString()))
                &&
                Boolean.TRUE.equals(follows.contains(currentUserId.toString()));

        if (flag){
            stringRedisTemplate.opsForSet().remove(fansKey,userId.toString());
            stringRedisTemplate.opsForSet().remove(followsKey,currentUserId.toString());
        }
        return true;
    }

}




